package com.treasure.mall.zbqmallmanager.controller.merchant;

import com.treasure.mall.biz.base.UserDetails;
import com.treasure.mall.biz.dto.condition.AdvanceLogSearchCondition;
import com.treasure.mall.biz.dto.condition.DepositLogCondition;
import com.treasure.mall.biz.dto.condition.MerchantSearchCondition;
import com.treasure.mall.biz.entity.embeddable.ReceivingInfo;
import com.treasure.mall.biz.entity.log.AdvanceLogPO;
import com.treasure.mall.biz.entity.product.CategoryPO;
import com.treasure.mall.biz.entity.user.DepositLogPO;
import com.treasure.mall.biz.entity.user.MerchantPO;
import com.treasure.mall.biz.service.core.log.AdvanceLogService;
import com.treasure.mall.biz.service.core.product.CategoryService;
import com.treasure.mall.biz.service.core.user.DepositLogService;
import com.treasure.mall.biz.service.core.user.MerchantService;
import com.treasure.mall.zbq.common.base.ApiResult;
import com.treasure.mall.zbq.common.constant.Constant;
import com.treasure.mall.zbq.common.ienum.base.CodeDescEnumHelper;
import com.treasure.mall.zbq.common.ienum.live.LiveEnums;
import com.treasure.mall.zbq.common.ienum.log.LogDataType;
import com.treasure.mall.zbq.common.oss.ResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;

/**
 *
 * +---------------------------------------------------------
 * * @package: com.treasure.mall.zbqmallmanager.controller.merchant
 * * @author: guomw (guomwchen@foxmail.com)
 * * @date: 2020/6/14 22:32
 * * @since: V1.0.0
 * +---------------------------------------------------------
 * 注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的
 * Copyright 2019-2022 com.treasure.mall.zbqmallmanager.controller.merchant Inc. All rights reserved.
 */
@Controller
@RequestMapping("/merchant")
public class MerchantController {

    @Resource
    private MerchantService merchantService;
    @Resource
    private ResourceService resourceService;
    @Autowired
    private DepositLogService depositLogService;
    @Autowired
    private CategoryService categoryService;

    /**
     * 获取商户列表
     *
     * @param condition
     * @param pageIndex
     * @param model
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list(@ModelAttribute("condition") MerchantSearchCondition condition,
                       @RequestParam(required = false, defaultValue = "1") int pageIndex,
                       @RequestParam(required = false, defaultValue = "1") int dataType,
                       Model model) {
        //1= 等于商户列表  否则为审核列表
        if (dataType == 1) {
            condition.setStatus(LiveEnums.AuditStatus.SUCCESS.getCode());
        } else {
            condition.setStatus(LiveEnums.AuditStatus.WAIT.getCode());
        }
        Page<MerchantPO> userPOS = merchantService.findAll(pageIndex, Constant.DEFAULT_PAGE_SIZE, condition);
        model.addAttribute("pageIndex", pageIndex);
        model.addAttribute("totalRecords", userPOS.getTotalElements());
        model.addAttribute("totalPages", userPOS.getTotalPages());
        model.addAttribute("list", userPOS.getContent());
        model.addAttribute("dataType", dataType);
        return "merchant/merchant_list";
    }

    /**
     * 商户详情
     *
     * @param id
     * @param model
     * @return
     */
    @RequestMapping(value = "/detail", method = RequestMethod.GET)
    public String detail(@RequestParam(required = true) Long id, Model model) {
        MerchantPO po = merchantService.findById(id);
        model.addAttribute("model", po);
        return "merchant/merchant_detail";
    }

    @Autowired
    private AdvanceLogService advanceLogService;

    /**
     * 余额明细
     *
     * @param type      1：余额明细，2：待入账明细
     * @param condition
     * @param pageIndex
     * @param model
     * @return
     */
    @RequestMapping(value = "/detail/advanceLog/{type}", method = RequestMethod.GET)
    public String advanceLogs(@PathVariable("type") int type,
                              @ModelAttribute("condition") AdvanceLogSearchCondition condition,
                              @RequestParam(required = false, defaultValue = "1") int pageIndex, Model model) {
        condition.setDataType(CodeDescEnumHelper.getEnumTypeByCode(LogDataType.class, type));

        Page<AdvanceLogPO> advanceLogPOS = advanceLogService.findAll(pageIndex, Constant.DEFAULT_PAGE_SIZE, condition);
        MerchantPO po = merchantService.findById(condition.getUserId());
        model.addAttribute("model", po);
        model.addAttribute("pageIndex", pageIndex);
        model.addAttribute("totalRecords", advanceLogPOS.getTotalElements());
        model.addAttribute("totalPages", advanceLogPOS.getTotalPages());
        model.addAttribute("logs", advanceLogPOS.getContent());
        model.addAttribute("type", type);

        return "merchant/merchant_detail_payment";
    }

    @RequestMapping(value = "/audit", method = RequestMethod.GET)
    public String audit(@RequestParam(required = true) Long id, Model model) {
        model.addAttribute("merchantId", id);
        return "merchant/merchant_audit";
    }

    @PostMapping("/audit")
    @ResponseBody
    public ApiResult modifyAudit(@RequestParam Long id,
                                 @RequestParam int status,
                                 String reason) {
        LiveEnums.AuditStatus auditStatus = CodeDescEnumHelper.getEnumTypeByCode(LiveEnums.AuditStatus.class, status);
        boolean b = merchantService.modifyAuditStatus(id, auditStatus, reason);
        if (b) {
            return ApiResult.ok();
        }
        return ApiResult.error("操作失败");

    }

    @PostMapping("/resetPass")
    @PreAuthorize("hasRole('ADMIN')")
    @ResponseBody
    public ApiResult resetPassword(Long merchantId) {
        merchantService.resetPassword(merchantId);

        return ApiResult.ok();
    }

    @PostMapping("/modify/mainCategory")
    @PreAuthorize("hasRole('ADMIN')")
    @ResponseBody
    public ApiResult modifyMainCategory(Long merchantId, Long categoryId) {
        merchantService.modifyMainCategory(merchantId, categoryId);
        return ApiResult.ok();
    }

    @GetMapping("/balance")
    @PreAuthorize("hasRole('MERCHANT')")
    @ResponseBody
    public ApiResult balance(@AuthenticationPrincipal UserDetails userDetails) {
        MerchantPO merchantPO = merchantService.findById(userDetails.getId());

        return ApiResult.ok(merchantPO.getBalance());
    }

    @GetMapping("/detail/depositLogs")
    public String depositLogs(
            @ModelAttribute("condition") DepositLogCondition condition,
            @RequestParam(required = false, defaultValue = "1") int pageIndex,
            Model model
    ) {

        Page<DepositLogPO> pos = depositLogService.findAll(pageIndex, Constant.DEFAULT_PAGE_SIZE, condition);
        MerchantPO po = merchantService.findById(condition.getMerchantId());
        model.addAttribute("model", po);
        model.addAttribute("pageIndex", pageIndex);
        model.addAttribute("totalRecords", pos.getTotalElements());
        model.addAttribute("totalPages", pos.getTotalPages());
        model.addAttribute("logs", pos.getContent());

        return "merchant/merchant_detail_deposit";
    }

    /**
     * 开启或或关闭客服
     *
     * @param merchantId
     * @return
     */
    @GetMapping("/toggleContact")
    @ResponseBody
    public ApiResult toggleContactStatus(Long merchantId) {
        merchantService.toggleContactStatus(merchantId);
        return ApiResult.ok();
    }

    /**
     * 修改订单收货地址
     *
     * @param merchantId
     * @param receivingInfo
     * @return
     */
    @PostMapping("/update/returnedPurchase")
    @ResponseBody
    public ApiResult updateReturnedPurchaseAddress(Long merchantId, ReceivingInfo receivingInfo) {
        merchantService.updateReturnedPurchaseAddress(merchantId, receivingInfo);
        return ApiResult.ok();
    }

    /**
     * 设置佣金抽成比例
     *
     * @param roomId
     * @param model
     * @return
     */
    @GetMapping("/rate/edit")
    @PreAuthorize("hasRole('ADMIN')")
    public String editRate(Long merchantId, Model model) {
        MerchantPO po = merchantService.findById(merchantId);
        Long catId = po.getData().getMainCategory().getCatId();
        BigDecimal rebateRateOne = po.getRebateRateOne();
        BigDecimal rebateRateTwo = po.getRebateRateTwo();
        BigDecimal commissionRate = po.getCommissionRate();
        CategoryPO categoryPO = categoryService.getRootCategory(catId);
        if (po.getRebateRateOne() == null) {
            rebateRateOne = categoryPO.getRebateRateOne();
        }
        if (po.getRebateRateTwo() == null) {
            rebateRateTwo = categoryPO.getRebateRateTwo();
        }
        if (po.getCommissionRate() == null) {
            commissionRate = categoryPO.getCommissionRate();
        }
        model.addAttribute("merchantId", merchantId);
        model.addAttribute("commissionRate", commissionRate);
        model.addAttribute("rebateRateOne", rebateRateOne);
        model.addAttribute("rebateRateTwo", rebateRateTwo);
        model.addAttribute("platformRemain", BigDecimal.valueOf(100).subtract(rebateRateOne).subtract(rebateRateTwo).abs());
        return "merchant/merchant_edit_rate";
    }

    /**
     * 保存佣金抽成比例
     *
     * @param roomId
     * @param commissionRate
     * @param rebateRateOne
     * @param rebateRateTwo
     * @return
     */
    @PostMapping("/rate/edit/{merchantId}")
    @ResponseBody
    @PreAuthorize("hasRole('ADMIN')")
    public ApiResult editRate(@PathVariable Long merchantId, BigDecimal commissionRate, BigDecimal rebateRateOne, BigDecimal rebateRateTwo) {
        if (commissionRate == null) {
            return ApiResult.error("请输入抽成比例");
        }
        merchantService.setRewardRate(merchantId, commissionRate, rebateRateOne, rebateRateTwo);
        return ApiResult.ok();
    }


}
